<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/**
 * Description:
 *
 * @author      Eden
 * @datetime    2016/11/28 15:02
 * @copyright   Beijing CmsTop Technology Co.,Ltd.
 */

class Admin_Model extends ADM_Model
{
    /**
     * 初始化
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 获取列表
     * @param array $options
     * @return array
     */
    public function getLists(Array $options)
    {
        $db = clone($this->db);
        $query = $this->db
            ->join('admin_profile', 'admin_profile.adminId = admin.id')
            ->order_by('admin.id', 'DESC')
            ->limit($options['limit'], $options['offset']);

        if (!empty($options['admin'])) {
            $query->like('nickName', $options['admin']);
        }

        if (!empty($options['role']) && !empty($options['baseId']) && $options['role'] == 'base') {
            $query->where('baseId', $options['baseId']);
        }

        $query = $query->get('admin');

        return array(
            'data' => $this->_afterGetLists($query->result_array()),
            'total' => $db->count_all_results('admin')
        );
    }

    public function getRoles()
    {
        $query = $this->db->get_where('admin_role');
        return $query->result_array();
    }

    /**
     * 获取角色信息
     * @return array
     */
    public function formatRoles()
    {
        $rows = $this->getRoles();
        $results = array();
        if (!empty($rows)) foreach($rows as $row) {
            $id = $row['id'];
            $results[$id] = $row['role'];
        }
        return $results;
    }

    /**
     * 处理列表数据
     * @param $lists
     * @return array
     */
    private function _afterGetLists($lists)
    {
        $result = array();
        $roles = $this->formatRoles();
        $this->load->library('core/upload', null, 'up');
        if (!empty($lists)) foreach($lists as &$list) {
            $data = array();
            $data['id'] = (int) value($list, 'id');
            $data['baseId'] = intval($list['baseId']);
            $data['roleId'] = (int) value($list, 'roleId');
            $data['role'] = array_key_exists($list['roleId'], $roles) ? $roles[$list['roleId']] : '管理员';
            $data['email'] = value($list, 'email');
            $data['phone'] = value($list, 'phone');
            $data['nickName'] = value($list, 'nickName');
            $data['created'] = value($list, 'created');
            $data['lastTime'] = value($list, 'lastTime');
            $data['lastIP'] = value($list, 'lastIP');
            $data['status'] = $list['status'] == 1 ? true : false;
            $data['avatar'] = thumb($list['avatar'], 100, 100);
            array_push($result, $data);
        }
        return $result;
    }

    /**
     * 编辑
     * @param array $params
     * @return bool
     */
    public function edit($params = array())
    {
        $this->db->trans_start();
        $upAdmin = clone($this->db);
        $adminData = array(
            'nickName' => value($params, 'nickName'),
            'email' => value($params, 'email'),
            'roleId' => value($params, 'roleId'),
        );

        if (!empty($params['password'])) {
            $password = encryptPassword($params['password']);
            $adminData = array_merge($adminData, $password);
        }

        $upAdmin->where('id', $params['id']);
        $resAdmin = $upAdmin->update('admin', $adminData);

        $upProfile = clone($this->db);
        $upProfile->where('adminId', $params['id']);
        $profileData = array(
            'avatar' => $params['avatar'],
            'phone' => $params['phone']
        );
        $resPro = $upProfile->update('admin_profile', $profileData);
        $this->db->trans_complete();

        if ($this->db->trans_status() === FALSE) {
            return false;
        }

        return $resAdmin || $resPro;
    }

    public function add($params = array())
    {
        $this->db->trans_start();
        $addAdmin = clone($this->db);
        $adminData = array(
            'nickName' => value($params, 'nickName'),
            'email' => value($params, 'email'),
            'roleId' => value($params, 'roleId'),
            'created' => date('Y-m-d H:i:s'),
            'lastTime' => date('Y-m-d H:i:s'),
            'lastIP' => remoteAddr(),
        );
        $adminData = array_merge($adminData, encryptPassword($params['password']));
        $addAdmin->insert('admin', $adminData);

        $lastId = $addAdmin->insert_id();

        $addProfile = clone($this->db);
        $profileData = array(
            'adminId' => $lastId,
            'avatar' => $params['avatar'],
            'phone' => $params['phone']
        );
        $addProfile->insert('admin_profile', $profileData);
        $this->db->trans_complete();

        if ($this->db->trans_status() === FALSE) {
            return false;
        }

        // 成功
        return true;
    }

}
